//
//  ZHLEETabBarItem.swift
//  ZHLEE_Blog_Swift_Pro
//
//  Created by ZHLEEBlander on 15/10/16.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit

class ZHLEETabBarItem: UITabBarItem {

    
    var index: Int = 0
    
    override var badgeValue: String? {
    
        didSet{
        
            setTabBarView()
        }
    }
    
    /**
    设置tabBar->_UIBadgeView的背景图片
    */
    private func setTabBarView(){
        
        let target = self.valueForKeyPath("_target") as! UITabBarController
        
        for tabBarChild in target.tabBar.subviews {
            
            if tabBarChild.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                for tabBarButtonChild in tabBarChild.subviews {
                    
                    if tabBarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!){
                        
                        for badgeViewChild in tabBarButtonChild.subviews {
                            
                            if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!){
                                
                                //运行时,查询\修改 对象属性
                                var count: UInt32 = 0
                                
                                //获取类身上的实例变量
                                let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
                                
                                //                                printLog("\(count)个变量")
                                for i in 0..<count{
                                    
                                    let ivar = ivars[Int(i)]
                                    
                                    //获取ivar的名称
                                    let ivarName = NSString(CString: ivar_getName(ivar), encoding: NSUTF8StringEncoding)
                                    
                                    //获取ivar类型
                                    //                                    let ivarType = NSString(CString: ivar_getTypeEncoding(ivar), encoding: NSUTF8StringEncoding)
                                    
                                    if ivarName!.isEqualToString("_image"){
                                        
                                        badgeViewChild.setValue(UIImage(named: "main_badge"), forKeyPath: (ivarName! as String))
                                    }
                                }
                                
                            }
                        }
                    }
                    
                }
            }
        }
        
    }
}
